package com.itcam.interview.pro00.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author : Cammy.Wu
 * Description : 
 */

public class CompletableFutureOtherMethods {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建一个有返回值的 CompletableFuture
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return 10;
        });

        // 1. thenApply 和 thenApplyAsync
        // thenApply 用于对结果进行转换，同步执行
        CompletableFuture<Integer> thenApplyFuture = future.thenApply(result -> result * 2);
        System.out.println("thenApply result: " + thenApplyFuture.get());
        // thenApplyAsync 异步执行转换操作
        CompletableFuture<Integer> thenApplyAsyncFuture = future.thenApplyAsync(result -> result * 3);
        System.out.println("thenApplyAsync result: " + thenApplyAsyncFuture.get());

        // 2. thenCompose
        // thenCompose 用于组合多个 CompletableFuture
        CompletableFuture<Integer> thenComposeFuture = future.thenCompose(result ->
                CompletableFuture.supplyAsync(() -> result + 5));
        System.out.println("thenCompose result: " + thenComposeFuture.get());

        // 3. thenCombine
        // thenCombine 用于合并两个 CompletableFuture 的结果
        CompletableFuture<Integer> anotherFuture = CompletableFuture.supplyAsync(() -> 20);
        CompletableFuture<Integer> thenCombineFuture = future.thenCombine(anotherFuture, (res1, res2) -> res1 + res2);
        System.out.println("thenCombine result: " + thenCombineFuture.get());

        // 4. allOf
        // allOf 用于等待所有 CompletableFuture 完成
        CompletableFuture<Void> allOfFuture = CompletableFuture.allOf(future, anotherFuture);
        allOfFuture.get();
        System.out.println("allOf completed");

        // 5. anyOf
        // anyOf 用于只要有一个 CompletableFuture 完成就继续
        CompletableFuture<Object> anyOfFuture = CompletableFuture.anyOf(future, anotherFuture);
        System.out.println("anyOf result: " + anyOfFuture.get());

        // 6. exceptionally
        // exceptionally 用于处理异常情况
        CompletableFuture<Object> exceptionFuture = CompletableFuture.supplyAsync(() -> {
            throw new RuntimeException("Simulated exception");
        }).exceptionally(ex -> {
            System.out.println("Exception caught: " + ex.getMessage());
            return 0;
        });
        System.out.println("exceptionally result: " + exceptionFuture.get());
    }
}
